package com.Tread;

import java.util.Arrays;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 一个银行有多个账户
 *
 */
public class Bank {

    private ReentrantLock bankLock;
    private final double[] accounts;
    private Condition condition;

    /**
     * 构造一个银行，并初始化
     * @param n
     * @param initialBalance
     */ 
    public Bank(int n,double initialBalance) {
        accounts = new double[n];

        //将每个元素都初始化

        Arrays.fill(accounts,initialBalance);

        //设置锁

        bankLock = new ReentrantLock();

        condition = bankLock.newCondition();
    }

    //之前的写法     虽然总额不变，但是有可能某一账户为负值，
    public  void transfer(int from,int to,double amount)throws InterruptedException{
        //编程技巧

        //最原始的并发，启动顺序和执行顺序

        //这样会造成排他性访问

        while (accounts[from] < amount)
            condition.wait();

            //打印当前线程
            System.out.print(Thread.currentThread());
            accounts[from] -= amount;

            //transfer可能执行到中间就被中断

            System.out.printf(" %10.2f from %d to %d", amount, from, to);
            accounts[to] += amount;

            //打印当前总余额，应该是一个定值
            System.out.printf("Total balance: %10.2f\n", this.getTotalBalance());
        condition.notify();
        }

    public double getTotalBalance(){
        bankLock.lock();
        try {

            double sum = 0;
            for (double e : accounts) {
                sum += e;
            }
            return sum;
        }
        finally {
            bankLock.unlock();
        }
    }

    public int size(){
        return accounts.length;
    }
}
